package com.java.work01.Filter;

import com.java.work01.service.LoginServiceImpl;
import com.java.work01.util.CookieUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        if(request.getRequestURI().contains("login")) {//如果访问login,直接放行
            filterChain.doFilter(request, response);
            return;
        }else {
            String username = (String) request.getSession().getAttribute("username");
            if(username==null) {//sesion中没有，去Cookie中找
                String val = CookieUtils.getCookieValByKey("auto", request);
                if(val!= null&& !val.equals("")) {
                    String name = val.split("_")[0];
                    String pass = val.split("_")[1];

                    if(new LoginServiceImpl().login(name, pass)) {//重新验证登录
                        request.getSession().setAttribute("username", name);//登录成功，放入Session，并放行
                        filterChain.doFilter(request, response);
                        return;
                    }else {//验证失败，重新登录
                        response.sendRedirect("login.jsp");
                    }
                }else {//Cookie中也没有，第一次访问，跳转登录页面
                    response.sendRedirect("login.jsp");
                }
            }else {//session中有，放行
                filterChain.doFilter(request, response);
                return;
            }
        }
    }

    @Override
    public void destroy() {

    }
}
